package com.crois.barrier.web.handler;

import com.crois.barrier.common.dto.PluginData;
import com.crois.barrier.common.enums.PluginEnum;
import com.crois.barrier.common.utils.GsonUtils;
import com.crois.barrier.common.utils.Singleton;
import com.crois.barrier.metrics.config.MetricsConfig;
import com.crois.barrier.metrics.facade.MetricsTrackerFacade;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2021/4/22
 */
public class MonitorPluginDataHandler implements PluginDataHandler{


    @Override
    public void handle(final PluginData pluginData) {
        if (Objects.nonNull(pluginData) && pluginData.getEnabled()) {
            MetricsConfig monitorConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), MetricsConfig.class);
            if (!checkConfig(monitorConfig)) {
                return;
            }
            if (!MetricsTrackerFacade.getInstance().isStarted()) {
                start(monitorConfig);
            } else  if (!monitorConfig.equals(Singleton.INST.get(MetricsConfig.class))) {
                restart(monitorConfig);
            }
        } else {
            stop();
        }
    }

    @Override
    public String pluginNamed() {
        return PluginEnum.MONITOR.getName();
    }
    private boolean checkConfig(final MetricsConfig monitorConfig) {
        return Objects.nonNull(monitorConfig)
                && StringUtils.isNoneBlank(monitorConfig.getHost())
                && Objects.nonNull(monitorConfig.getPort())
                && Objects.nonNull(monitorConfig.getAsync());
    }
    private void restart(final MetricsConfig monitorConfig) {
        stop();
        start(monitorConfig);
    }

    private void start(final MetricsConfig monitorConfig) {
        MetricsTrackerFacade.getInstance().start(monitorConfig);
        Singleton.INST.single(MetricsConfig.class, monitorConfig);
    }

    private void stop() {
        MetricsTrackerFacade.getInstance().stop();
    }
}
